package com.salton123.soulove.sailfish.video.ui.fm

import android.os.Bundle
import android.text.format.Formatter
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.observe
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.facade.annotation.Route
import com.lxj.xpopup.XPopup
import com.salton123.revenue.RevenueFacade
import com.salton123.soulove.api.RouterManager
import com.salton123.soulove.app.R
import com.salton123.soulove.common.Constants
import com.salton123.soulove.common.adapter.SmartRefreshDelegate
import com.salton123.soulove.sailfish.db.SailfishDatabase
import com.salton123.soulove.sailfish.video.SailfishManager
import com.salton123.soulove.sailfish.video.ui.adapter.VideoHomeHorizontalAdapter
import com.salton123.soulove.utils.Utils
import com.salton123.ui.base.BaseFragment
import com.salton123.util.PreferencesUtils
import kotlinx.android.synthetic.main.adapter_item_recycler_menu.*
import kotlinx.android.synthetic.main.salton_layout_refresh_loadmore.*
import kotlinx.android.synthetic.main.xmly_layout_main_custom_toolbar.*
import kotlinx.coroutines.launch

/**
 * Time:9/12/21 10:35 AM
 * Author:
 * Description:
 */
@Route(path = Constants.Router.Video.HOME)
class VideoHomeFragment : BaseFragment(), SmartRefreshDelegate {
    override fun isAsyncContentView(): Boolean = false
    private val videoHomeHorizontalAdapter by lazy { VideoHomeHorizontalAdapter() }
    override fun loadData(isRefresh: Boolean) {
    }

    override fun getLayoutId(): Int = R.layout.fragment_video_recycler

    override fun initViewAndData(savedInstanceState: Bundle?) {
        initRefreshDelegate(recyclerView, smartRefreshLayout, videoHomeHorizontalAdapter)
        setListener(tvSortOrder, ivEditAll, ivListAll, rbSearch, rbSetting)
        recyclerView.setHasFixedSize(true)
        (recyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        setAdapterData()
        tvSortOrder.text = Utils.sortText()
        SailfishDatabase.Impl.videoDao().totalSize()?.observe(this@VideoHomeFragment) { size ->
            size?.let {
                tvClearInfo?.text = getString(
                    R.string.clear_remind,
                    Formatter.formatFileSize(activity(), SailfishManager.getDeleteSize()),
                    Formatter.formatFileSize(activity(), it)
                )
            }
        }
    }

    var isLeftRightLayout = true
    override fun onClick(view: View?) {
        super.onClick(view)
        when (view) {
            tvSortOrder -> {
                XPopup.Builder(activity())
                    .isDestroyOnDismiss(true)
                    .asBottomList(
                        getString(R.string.video_sort_order),
                        Utils.sortList(),
                        null,
                        PreferencesUtils.getInt("sort_position", 0)
                    ) { position, text ->
                        PreferencesUtils.putInt("sort_position", position)
                        tvSortOrder.text = Utils.sortText()
                        setAdapterData()
                    }.show()
            }
            rbSearch -> {
                val param = Utils.sortParam()
                SailfishDatabase.Impl.videoDao().loadAll(param.first, param.second).apply {
                    observe(this@VideoHomeFragment) {
                        SailfishManager.toBatchOperateList = it
                        RouterManager.batchOperate(activity(), "")
                        removeObservers(this@VideoHomeFragment)
                    }
                }
            }
            rbSetting -> {
                RevenueFacade.show(activity())
//                RouterManager.setting(activity())
            }
            ivEditAll -> {
                val param = Utils.sortParam()
                SailfishDatabase.Impl.videoDao().loadAll(param.first, param.second).apply {
                    observe(this@VideoHomeFragment) {
                        SailfishManager.toBatchOperateList = it
                        RouterManager.batchOperate(activity(), "")
                        removeObservers(this@VideoHomeFragment)
                    }
                }
            }
            ivListAll -> {
                isLeftRightLayout = !isLeftRightLayout
                setAdapterData()
            }
        }
    }

    private fun setAdapterData() {
        lifecycleScope.launch {
            recyclerView.adapter = videoHomeHorizontalAdapter
            videoHomeHorizontalAdapter.setDiffCallback(object : DiffUtil.ItemCallback<String>() {
                override fun areItemsTheSame(oldItem: String, newItem: String): Boolean {
                    return oldItem == newItem
                }

                override fun areContentsTheSame(oldItem: String, newItem: String): Boolean {
                    return oldItem == newItem
                }
            })
            SailfishDatabase.Impl.videoDao().loadDirs().observe(this@VideoHomeFragment) {
                videoHomeHorizontalAdapter.setDiffNewData(it)
            }
        }
    }
}